package com.css.fxfzypg.modules.similitudeAnalyse.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.HisEarDamResult;
import com.css.fxfzypg.modules.similitudeAnalyse.param.QueParams;
import com.css.fxfzypg.modules.similitudeAnalyse.repository.HisEarDamResultRepository;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class HisEarDamResultRepositoryImpl implements HisEarDamResultRepository {
    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Override
    public void save(HisEarDamResult hisEarDamResult) {
        String sql = "insert into ypg_earthquake_disaster_result(id,real_time,real_earthquake_level,real_longitude,real_latitude,real_depth," +
                "real_location, distance, jeds_id, event_abbreviation,jeds_date,jeds_time, jeds_longitude, jeds_latitude, magnitude, " +
                "reference_position, depth, maximum_intensity, dead_number, cause_of_death, injuries, num_resettled, rescue_force_input, " +
                "medical_force_input, loss_volume, infrastructure_damage, geological_hazard_situation, secondary_fire, secondary_flood, " +
                "secondary_explosion, hazardous_chemicals_leaked, des_earthquake_damage, note, jeds_zhzp, isoline, isoline_pic, intensity_map, " +
                "attachment, location, location1,real_province,province) " +
                "values(:id, :realTime, :realEarthquakeLevel, :realLongitude, :realLatitude, :realDepth, :realLocation, :distance, :jedsId, " +
                ":eventAbbreviation, :jedsDate, :jedsTime, :jedsLongitude, :jedsLatitude, :magnitude, :referencePosition, :depth, :maximumIntensity, " +
                ":deadNumber, :causeOfDeath, :injuries, :numResettled, :rescueForceInput, :medicalForceInput, :lossVolume, :infrastructureDamage, " +
                ":geologicalHazardSituation, :secondaryFire, :secondaryFlood, :secondaryExplosion, :hazardousChemicalsLeaked, :desEarthquakeDamage, " +
                ":note, :jedsZhzp, :isoline, :isolinePic, :intensityMap, :attachment, :location, :location1, :realProvince, :province)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(hisEarDamResult);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void deleteAllData() {
        String sql = "delete from ypg_earthquake_disaster_result";
        jdbcTemplate.update(sql);
    }

    @Override
    public Map<String, Object> getPage(QueParams queParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from ypg_earthquake_disaster_result");
        StringBuilder whereSql = new StringBuilder(" where 1=1");
        StringBuilder orderSql = new StringBuilder(" order by real_time desc,distance desc");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;
        StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
        if (!PlatformObjectUtils.isEmpty(queParams.getMinRealEarthquakeLevel())) {
            whereSql.append(" and cast(magnitude as decimal) >= "+ queParams.getMinRealEarthquakeLevel()+" ");
        }
        if (!PlatformObjectUtils.isEmpty(queParams.getMaxRealEarthquakeLevel())) {
            whereSql.append(" and cast(magnitude as decimal) <= "+ queParams.getMaxRealEarthquakeLevel()+" ");
        }
        if (!PlatformObjectUtils.isEmpty(queParams.getRealLocation())) {
            whereSql.append(" and real_location like '%" + queParams.getRealLocation() + "%'");
        }
        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if(roles.contains(FxfzConstants.YPG_PRI_YW_ROLE) || roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)){
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if (!PlatformObjectUtils.isEmpty(areaNameByAreaId)) {
                whereSql.append(" and real_province like '%" + areaNameByAreaId + "%' and province like '%" + areaNameByAreaId + "%'");
            }
        }

        //时间范围
        if (!PlatformObjectUtils.isEmpty(queParams.getStartTime()) & !PlatformObjectUtils.isEmpty(queParams.getEndTime())) {
            whereSql.append("and real_time between '" + queParams.getStartTime() + "' and '" + queParams.getEndTime() + "'");
        }
        //大于开始时间
        if (!PlatformObjectUtils.isEmpty(queParams.getStartTime()) & PlatformObjectUtils.isEmpty(queParams.getEndTime())) {
            whereSql.append("and real_time  >='" + queParams.getStartTime() + "'");
        }
        //小于结束时间
        if ( !PlatformObjectUtils.isEmpty(queParams.getEndTime()) & PlatformObjectUtils.isEmpty(queParams.getStartTime())) {
            whereSql.append("and real_time  <='" + queParams.getEndTime() + "'");
        }


        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(HisEarDamResult.class)).size();
        List<HisEarDamResult> list = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(HisEarDamResult.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public HisEarDamResult fingById(String id) {
        String sql = "select * from ypg_earthquake_disaster_result where id = ? ";
        HisEarDamResult hisEarDamResult = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(HisEarDamResult.class), id);
        return hisEarDamResult;
    }
}
